<template>
	<div>
		<!--搜索表单-->
		<div>
			<el-form ref="queryForm" :inline="true" :model="queryForm" size="mini" label-width="70px">
				<el-form-item label="订单编号" prop="orderId">
					<el-input v-model="queryForm.orderId" placeholder="请输入订单编号" clearable></el-input>
				</el-form-item>
				<el-form-item label="订单状态" prop="status">
					<el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
						<el-option v-for="(item, index) in states" :key="index" :label="item.dicDataLabel"
							:value="item.dicDataVal"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="订单类型" prop="orderType">
					<el-select v-model="queryForm.orderType" placeholder="请选择类型" clearable>
						<el-option v-for="(item, index) in orderTypes" :key="index" :label="item.dicDataLabel"
							:value="item.dicDataVal"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="支付方式" prop="pay">
					<el-select v-model="queryForm.pay" placeholder="请选择类型" clearable>
						<el-option v-for="(item, index) in pays" :key="index" :label="item.dicDataLabel"
							:value="item.dicDataVal"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="下单时间" prop="createTimeArray">
					<el-date-picker type="daterange" v-model="queryForm.createTimeArray" format="yyyy-MM-dd"
						value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
						clearable></el-date-picker>
				</el-form-item>
				<el-form-item size="small">
					<el-button type="primary" @click="buildOrderTableData" v-hasPremission="'sale:order:list'" >提交</el-button>
					<el-button @click="resetForm">重置</el-button>
				</el-form-item>
			</el-form>
			<el-button type="success" plain size="small" v-hasPremission="'sale:order:upLoad'" @click="showImportDialog" >导入</el-button>
			<el-button type="success" plain size="small" v-hasPremission="'sale:order:template'" @click="excelTemplateDownload">下载模板</el-button>
			<span style="color:red">说明：订单状态为已付款时，可以生成出库单；生成出库单后订单状态为待出库；需要进行拣货(拣货是在生成商品串码),拣货完成后状态为发货中!</span>
			<!--订单数据-->
			<el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column label="序号" type="index" width="50">
				</el-table-column>
				<el-table-column prop="orderId" label="订单编号" width="180">
				</el-table-column>
				<el-table-column prop="orderType" label="订单类型" :formatter="formatterOrderType">
				</el-table-column>
				<el-table-column prop="pay" label="支付方式" :formatter="formatterPay">
				</el-table-column>
				<el-table-column prop="distribution" label="配送方式" :formatter="formatterDistribution">
				</el-table-column>
				<el-table-column prop="status" label="订单状态" :formatter="formatterState">
				</el-table-column>
				<el-table-column prop="totalMoney" label="订单金额">
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间">
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button size="mini"  @click="handleDetail(scope.row)">详情
						</el-button>
						<el-button size="mini"  type="warning" 
						v-if="scope.row.status == 1 "
							@click="handleDelivery(scope.row)">生成出库单</el-button>
					</template>
				</el-table-column>
			</el-table>
			</el-table>
			<!-- 分页 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryForm.pageNum" :page-sizes="[2, 5, 7, 9]" :page-size="queryForm.pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="queryForm.total">
			</el-pagination>
		</div>
		<!-- 数据表单 -->
		<el-dialog :title="titleName" :visible.sync="formVisible">
			<el-descriptions title="订单基本资料" column="2">
				<template slot="extra">
					<el-button type="primary" v-if="isDelivery" @click="wordDowload">生成出库单</el-button>
				</template>
				<template slot="extra">
					<el-button type="primary" v-if="formData.status==2" @click="deliveryFinish">拣货完成</el-button>
				</template>
				<el-descriptions-item label="订单编号">{{formData.orderId}}</el-descriptions-item>
				<el-descriptions-item label="订单类型">
					<span v-for="(item, index) in orderTypes" :key="index"
						v-if="item.dicDataVal == formData.orderType">{{item.dicDataLabel}}</span>
				</el-descriptions-item>

				<el-descriptions-item label="下单时间">
					<span>{{formData.createTime}}</span>
				</el-descriptions-item>

				<el-descriptions-item label="订单状态">
					<span v-for="(item, index) in states" :key="index"
						v-if="item.dicDataVal == formData.status">{{item.dicDataLabel}}</span>
				</el-descriptions-item>
			</el-descriptions>

			<el-descriptions title="收货人资料" column="2" size="medium">
				<el-descriptions-item label="收货人">{{formData.consignee}}</el-descriptions-item>
				<el-descriptions-item label="联系方式">{{formData.phone}}</el-descriptions-item>
				<el-descriptions-item label="邮政编码">{{formData.zipcode}}</el-descriptions-item>
				<el-descriptions-item label="收货地址">{{formData.area}}</el-descriptions-item>
				<el-descriptions-item label="收货区域">{{formData.region}}</el-descriptions-item>

				<el-descriptions-item label="支付方式">
					<span v-for="(item, index) in pays" :key="index"
						v-if="item.dicDataVal == formData.pay ">{{item.dicDataLabel}}</span>
				</el-descriptions-item>
				<el-descriptions-item label="配送方式">
					<span v-for="(item, index) in distributions" :key="index"
						v-if="item.dicDataVal == formData.distribution ">{{item.dicDataLabel}}</span>
				</el-descriptions-item>
			</el-descriptions>
			<el-descriptions title="商品详情" column="1" border="true">
				<el-descriptions-item colon="false">
					<el-table :data="formData.commodityList" tooltip-effect="dark" border="true" style="width: 100%">
						<el-table-column prop="goodsInfo.gcode" label="商品编码">
						</el-table-column>
						<el-table-column prop="goodsInfo.gname" label="商品名称">
						</el-table-column>
						<el-table-column prop="oneMoney" label="商品单价">
						</el-table-column>
						<el-table-column prop="num" label="商品数量">
						</el-table-column>
						<el-table-column prop="totalMoney" label="总金额">
						</el-table-column>
					</el-table>
				</el-descriptions-item>
			</el-descriptions>
			<div style="width: 100%;">
				<el-button type="primary" style="display:block;margin:10px auto" v-if="isDelivery"
					@click="wordDowload">生成出库单</el-button>
			</div>
		</el-dialog>
		<!-- Excel导入 -->
		<el-dialog title="导入产品excel" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
			<el-upload class="upload-demo" ref="upload" action="" :on-change="handleChange" :on-remove="handleRemove"
				:file-list="fileList" :auto-upload="false">
				<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
				<el-button style="margin-left: 10px;" size="small" type="success" @click="myupdateUpload">上传到服务器
				</el-button>
				<div slot="tip" class="el-upload__tip">只能上传elsx文件，且不超过2M</div>
			</el-upload>
			<div>
				<span>
					导入结果:[订单页记录数:{{importResult.orderNums}},成功:{{importResult.orderSucNums}},失败:{{importResult.orderErrorNum}}]
					<br/>
					[订单商品页记录数:{{importResult.orderCommodityNums}},成功:{{importResult.orderCommoditySucNums}},失败:{{importResult.orderCommodityErrorNum}}]
					<span v-show="importResult.orderErrorNum>0||importResult.orderCommodityErrorNum>0">
						, <el-link type="danger" @click="downloadErrorExcel()">查看失败记录</el-link>
					</span>
				</span>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		//数据模板
		data() {
			return {
				//键值对
				queryForm: {
					orderId: '',
					orderType: '',
					pay: '',
					status: '',
					createTimeArray: [],
					pageNum: 1,
					pageSize: 2,
					total: 0
				},
				tableData: [],
				//选中的行数据
				multipleSelection: [],
				orderTypes: [], //订单类型集合
				pays: [], // 支付方式集合
				states: [], //订单状态集合
				distributions: [], //配送方式
				formData: {
				},
				formVisible: false,
				titleName: '',
				isDelivery: false,
				dialogVisible: false,
				fileList: [],
				importResult: {
					orderNums: 0,
					orderSucNums: 0,
					orderErrorNum: 0,
					orderCommodityNums: 0,
					orderCommoditySucNums: 0,
					orderCommodityErrorNum: 0,
					bucketName: '',
					objectName: '',
				}

			};
		},
		//函数对象
		methods: {
			//重置表单
			resetForm() {
				this.$refs['queryForm'].resetFields()
				this.queryForm.deptId = null;
				this.buildOrderTableData();
			},
			// 表单查询
			querySubmit() {
				this.buildOrderTableData();
			},
			//发送查询语句
			buildOrderTableData() {
				axios.get("/order/list?" + this.qsString(this.queryForm)).then(response => {
					this.tableData = response.list;
					this.queryForm.pageNum = response.pageNum;
					this.queryForm.pageSize = response.pageSize;
					this.queryForm.total = response.total;
				})
			},
			// 正反选
			toggleSelection(rows) {
				if (rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row);
					});
				} else {
					this.$refs.multipleTable.clearSelection();
				}
			},
			//当前选中行
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			//页面大小
			handleSizeChange(val) {
				this.queryForm.pageSize = val;
				this.buildOrderTableData();
			},
			//当前页数 
			handleCurrentChange(val) {
				this.queryForm.pageNum = val;
				this.buildOrderTableData();
			},
			formatterOrderType(row, column, cellValue, index) {
				return this.parseItem(this.orderTypes, cellValue)
			},
			formatterState(row, column, cellValue, index) {
				return this.parseItem(this.states, cellValue)
			},
			formatterPay(row, column, cellValue, index) {
				return this.parseItem(this.pays, cellValue)
			},
			formatterDistribution(row, column, cellValue, index) {
				return this.parseItem(this.distributions, cellValue)
			},
			//选择的详情表单
			selectDetail() {
				this.titleName = "详情表单";
				this.$nextTick(() => {
					this.formData = JSON.parse(JSON.stringify(this.multipleSelection[0]));
				});
				this.formVisible = true
				this.isDelivery = false
			},
			//详情表单
			handleDetail(row) {
				this.titleName = '详情表单'
				axios.get("/order/orderGoods/"+row.orderId).then(resp=>{
					this.formData = resp.data;
					this.formVisible = true
					this.isDelivery = false
				})
			},
			//handleDetail
			handleDelivery(row) {
				this.titleName = '出库单'
				axios.get("/order/orderGoods/"+row.orderId).then(resp=>{
					this.formData = resp.data;
					this.formVisible = true
					this.isDelivery = true
				})
			},
			//excel文件下载
			wordDowload() {
				axios.post("/delivery",this.formData,{
					responseType: 'blob'
				}).then(res => {
					this.fileDownload(res)
					this.buildOrderTableData();
					this.formVisible = false;
				})
			},
			fileDownload(res) {
				let data = res.data // 这里后端对文件流做了一层封装，将data指向res.data即可
				if (!data) {
					return
				}
				let url = window.URL.createObjectURL(new Blob([data]))
				let a = document.createElement('a')
				a.style.display = 'none'
				a.href = url
				var content = res.headers['content-disposition'];
				var name = content && content.split(';')[1].split('filename=')[1];
				name=decodeURIComponent(name)
				a.setAttribute('download', name)
				document.body.appendChild(a)
				a.click() //执行下载
				window.URL.revokeObjectURL(a.href) //释放url
				document.body.removeChild(a) //释放标签
			},
			deliveryFinish(){
				axios.put("/delivery/deliveryFinish",this.formData).
				then(res => {
					if(res.code == 20000){
						this.suc("拣货成功");
					}else{
						this.error(res.msg);
					}
					this.buildOrderTableData();
					this.formVisible = false;
				})
			},
			excelTemplateDownload(){
				let uri = '/order/excelDownload?relName=orderTemplate.xlsx';
				this.excelDowload(uri)
			},
			//excel文件下载
			excelDowload(uri) {
				axios.get(uri, {
					responseType: 'blob'
				}).then(res => {
					this.fileDownload(res)
				})
			},
			// fileDownload(res) {
			// 	let url = window.URL.createObjectURL(new Blob([res.data]))
			// 	let a = document.createElement('a')
			// 	a.style.display = 'none'
			// 	a.href = url;
			// 	a.setAttribute('download', "订单模板.xlsx");
			// 	document.body.appendChild(a);
			// 	a.click();
			// 	window.URL.revokeObjectURL(a.href);
			// 	document.body.removeChild(a);
			// },
			handleChange(file, fileList) {
				this.fileList = fileList;
			},
			handleRemove(file, fileList) {
				this.fileList = fileList;
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done();
					})
					.catch(_ => {});
			},
			showImportDialog() {
				this.dialogVisible = true;
			},
			myupdateUpload() {
				if (this.fileList.length == 0) {
					this.error("选中文件进行上传");
					return false;
				}
				if (this.fileList.length > 1) {
					this.error("只能选择一个excel文件");
					return false;
				}
				//文件对象
				let file = this.fileList[0]
				//判断是否为.xlsx文件
				const isxlsx = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
				const isLt2M = file.size / 1024 / 1024 < 2;
			
				if (!isxlsx) {
					this.$message.error('上传文件只能是xlsx格式!');
					return
				}
				if (!isLt2M) {
					this.$message.error('上传文件大小不能超过 2MB!');
					return
				}
				let myForm = new FormData();
				myForm.append("file", file.raw);
				this.$axios.post("order/uploadExcel", myForm, {
						headers: {
							"Content-Type": "multipart/form-data"
						}
					})
					.then(resp => {
						if (resp.code == 20000) {
							this.$message.success('上传成功');
							
							this.importResult.orderNums = resp.data.orderNums;
							this.importResult.orderSucNums = resp.data.orderSucNums;
							this.importResult.orderErrorNum = resp.data.orderNums - resp.data.orderSucNums;
							
							this.importResult.orderCommodityNums = resp.data.orderCommodityNums;
							this.importResult.orderCommoditySucNums = resp.data.orderCommoditySucNums;
							this.importResult.orderCommodityErrorNum = resp.data.orderCommodityNums - resp.data.orderCommoditySucNums;
							this.importResult.objectName = resp.data.objectName;
						} else {
							this.$message.error(resp.msg);
						}
						this.querySubmit()
			
					})
			
			},
			downloadErrorExcel() {
				let uri = "/order/excelDownload?objectName=" + this.importResult.objectName + "&relName=导入失败记录.xlsx"
				this.excelDowload(uri)
			},
			queryListDowload() {
				axios.get("/order/queryExcelDownload?" + this.qsString(this.queryForm), {
					responseType: 'blob'
				}).then(response => {
					this.fileDownload(response);
				})
			},
		},
		//各种钩子函数
		mounted() {
			this.getDictItems("order_type").then(resp => {
				this.orderTypes = resp.data;
			});
			this.getDictItems("cnee_DeliMethod").then(resp => {
				this.pays = resp.data;
			});
			this.getDictItems("order_state").then(resp => {
				this.states = resp.data;
			});
			this.getDictItems("cnee_deli_way").then(resp => {
				this.distributions = resp.data;
			});
			this.buildOrderTableData();
		}
	}
</script>

<style>
</style>
